package com.flyme.module.base.provider.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.flyme.common.core.constants.CommonConstants;
import com.flyme.common.core.utils.ApiAssert;
import com.flyme.common.core.utils.ObjectUtils;
import com.flyme.core.base.supper.service.impl.BaseServiceImpl;
import com.flyme.module.base.client.entity.SysCompany;
import com.flyme.module.base.client.entity.SysUser;
import com.flyme.module.base.client.entity.SystemAccount;
import com.flyme.module.base.client.event.UserRegEvent;
import com.flyme.module.base.provider.mapper.SysCompanyMapper;
import com.flyme.module.base.provider.service.SysAccountService;
import com.flyme.module.base.provider.service.SysCompanyService;
import com.flyme.module.base.provider.service.SysUserService;
import com.flyme.module.base.provider.service.SysVipService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class SysCompanyServiceImpl extends BaseServiceImpl<SysCompanyMapper, SysCompany> implements SysCompanyService {
    @Autowired
    private SysVipService vipService;
    @Autowired
    private SysAccountService accountService;
    @Autowired
    private SysUserService userService;

    @Override
    public Boolean add(SysCompany company) {
        company.setExpiryDate(company.getExpiryDate());
        SystemAccount account = accountService.findByAccount(company.getCompTel());
        SysUser user = userService.findByMobile(company.getCompTel());
        if (ObjectUtils.isNotEmpty(account) || ObjectUtils.isNotEmpty(user)) {
            return false;
        }
        company.setStatus(CommonConstants.ENABLED);
        Boolean tag = save(company);
        String pwd = company.getCompTel().substring(company.getCompTel().length() - 6);
        vipService.addCompVip(company.getId(), 2L, company.getExpiryDate());
        applicationContext.publishEvent(new UserRegEvent(this, company.getCompTel(), company.getCompTel(), "UT_COMPANY", "bus", company.getId(), pwd, company.getCompName()));
        return tag;
    }

    @Override
    public Boolean update(SysCompany company) {
        if (company.getExpiryDate().length() < 12) {
            company.setExpiryDate(company.getExpiryDate() + " 01:01:01");
        }
        if(company.getStatus().equals(0)){//禁用状态
            company.setBefVipTime(company.getExpiryDate());
        }
        Boolean tag = saveOrUpdate(company);
        if(company.getStatus().equals(1)){//启用状态
            vipService.addCompVip(company.getId(), 2L, company.getExpiryDate());
        }
        applicationContext.publishEvent(new UserRegEvent(this, company.getCompTel(), company.getCompTel(), "UT_COMPANY", "bus", company.getId()));
        return tag;
    }


    @Override
    public Boolean delByIds(String[] ids) {
        ApiAssert.notNull("参数不能为空", ids);
        return removeByIds(CollectionUtil.toList(ids));
    }


}
